package p2p;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.mpisws.p2p.filetransfer.FileTransferCallback;

import catalogo.ArquivoCatalogo;
import catalogo.Catalogo;
import rice.p2p.util.rawserialization.SimpleInputBuffer;

/*
 * Recebimento do arquivo pelo peer
 */

public class SyncFileTransferCallback implements FileTransferCallback {
	private SyncFileApp app;
	
	public SyncFileTransferCallback(SyncFileApp app)
	{
		this.app = app;
	}
	
	public void messageReceived(ByteBuffer bb) 
	{
       // System.out.println("Message received: "+bb);
	}

	
	// Receive a new or modified file
	public void fileReceived(File f, ByteBuffer metadata) {
		try {
			String data[] = ((new SimpleInputBuffer(metadata)).readUTF()).split(":");
			
			// extract filename and timestamp from metadata
			String originalFileName = data[0];
			int ts = (new Integer(data[1])).intValue();			
			String localPath = app.catalogo.getrootDir();
			System.out.println("Arquivo Recebido: " + originalFileName);
			File destFile = new File(localPath, originalFileName);
			
			Boolean inCatalog = app.catalogo.getArquivos().containsKey(originalFileName);
			int oldTs = inCatalog ?  app.catalogo.get_timestamp(originalFileName) : -1;
			// backup the file			
			SyncFileBackup.MoveFileToBackup(destFile, oldTs);
			// write the file
			if (!f.renameTo(destFile))
				System.out.println("Arquivo recebido: *erro* ao gravar o arquivo em "+destFile.getAbsolutePath());
			// update the catalog
			ArquivoCatalogo novo = new ArquivoCatalogo(originalFileName, 
					Catalogo.FormatDate(destFile.lastModified()), 
					ts, Catalogo.STATUS_OK);
			app.catalogo.updateArquivo(novo);	
		} catch (IOException ioe) {
			System.out.println("Error deserializing file name. "+ioe);
		}
	}

	public void receiveException(Exception ioe) {
		System.out.println("FTC.receiveException() "+ioe);
	}
}
